package com.socket.nio.nio.chat.example2.server.handler;

import com.socket.nio.nio.chat.example2.message.LoginRequestMessage;
import com.socket.nio.nio.chat.example2.message.LoginResponseMessage;
import com.socket.nio.nio.chat.example2.server.service.UserServiceFactory;
import com.socket.nio.nio.chat.example2.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author Hexudong
 * @date 2025/5/18
 */
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage loginRequestMessage) {
    String username = loginRequestMessage.getUsername();
    String password = loginRequestMessage.getPassword();
    boolean login = UserServiceFactory.getUserService().login(username, password);
    LoginResponseMessage message;
    if (login) {
      SessionFactory.getSession().bind(ctx.channel(), username);
      message = LoginResponseMessage.builder()
          .success(true)
          .reason("登录成功")
          .build();
    } else {
      message = LoginResponseMessage.builder()
          .success(false)
          .reason("用户名或密码错误")
          .build();
    }
    ctx.writeAndFlush(message);
  }
}
